#!/usr/bin/env python

import sys
import os
localDir = os.path.dirname(__file__)
absDir = os.path.join(os.getcwd(), localDir)

import cherrypy
from genshi.template import TemplateLoader
loader = TemplateLoader('../html', auto_reload=True)

import cgi
import tempfile
import random

from importFromMBox import MBoxImporter

class myFieldStorage(cgi.FieldStorage):
    """Our version uses a named temporary file instead of the default
    non-named file; keeping it visibile (named), allows us to create a
    2nd link after the upload is done, thus avoiding the overhead of
    making a copy to the destination filename."""
    
    def make_file(self, binary=None):
        return tempfile.NamedTemporaryFile()

def noBodyProcess():
    """Sets cherrypy.request.process_request_body = False, giving
    us direct control of the file upload destination. By default
    cherrypy loads it to memory, we are directing it to disk."""
    cherrypy.request.process_request_body = False

cherrypy.tools.noBodyProcess = cherrypy.Tool('before_request_body', noBodyProcess)


class Root(object):
	#class used to display the index.html

    @cherrypy.expose
    def index(self):
        tmpl = loader.load('index.html')
        return tmpl.generate().render('html', doctype='html')


@cherrypy.expose
@cherrypy.tools.noBodyProcess()
def upload(couchdb=None, database=None, maillist=None, datafile=None):
	# method tosave an uploaded file containing email in MBox format to couchdb 
	cherrypy.response.timeout = 3600 #set the timeout to 1 hour

	#return str(couchdb) +"<br>" + str(database) + "<br>" + str(maillist) + "<br>"+ str(datafile.filename)

	# convert the header keys to lower case
	lcHDRS = {}
	for key, val in cherrypy.request.headers.iteritems():
		lcHDRS[key.lower()] = val
        
    # at this point we could limit the upload on content-length...
    # incomingBytes = int(lcHDRS['content-length'])
        
    # create our version of cgi.FieldStorage to parse the MIME encoded
    # form data where the file is contained
	formFields = myFieldStorage(fp=cherrypy.request.rfile, headers=lcHDRS, environ={'REQUEST_METHOD':'POST'}, keep_blank_values=True)
        
    # we now create a 2nd link to the file, using the submitted
    # filename; if we renamed, there would be a failure because
    # the NamedTemporaryFile, used by our version of cgi.FieldStorage,
    # explicitly deletes the original filename
	datafile = formFields['datafile']
	maillist = str(formFields['maillist'].value)
	couchdb = str(formFields['couchdb'].value)
	database = str(formFields['database'].value)

	# save the file in tmp
	rand = random.randint(1, 200)	
	os.link(datafile.file.name, '/tmp/'+str(rand)+datafile.filename)


	# save the mbox file in couchdb
	importer = MBoxImporter(maillist, '/tmp/'+str(rand)+datafile.filename, couchdb, database)
	r,db,tread,tdb = importer.saveInDatabase()

	#remove tmp file
	os.remove('/tmp/'+str(rand)+datafile.filename)	
        
	return "Mail read = " +str(r) + "<br> mail imported = "+str(db)+"<br> time to read: "+str(tread)+"<br> time to save in database: "+str(tdb)


# remove any limit on the request body size; cherrypy's default is 100MB
# (maybe we should just increase it ?)
cherrypy.server.max_request_body_size = 0

# increase server socket timeout to 60s; we are more tolerant of bad
# quality client-server connections (cherrypy's defult is 10s)
cherrypy.server.socket_timeout = 60

conf = os.path.join(os.path.dirname(__file__), 'server.config')

root = Root()
root.upload = upload

cherrypy.tree.mount(root, '/', config=conf)
cherrypy.engine.start()
cherrypy.engine.block()



